import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:winkai/db/dao/ses_dao.dart';
import 'package:winkai/db/db_ext.dart';
import 'package:winkai/entity/msg_constant.dart';
import 'package:winkai/entity/role_info.dart';
import 'package:winkai/helper/chat_helper.dart';
import 'package:winkai/helper/iap/iap_helper.dart';
import 'package:winkai/helper/user_helper.dart';
import 'package:winkai/res/app_colors.dart';
import 'package:winkai/res/dimens.dart';
import 'package:winkai/ui/msg/controller/msg_controller.dart';
import 'package:winkai/utils/date_util.dart';
import 'package:winkai/utils/net_image_load_utils.dart';
import 'package:winkai/widget/empty_layout.dart';
import 'package:winkai/widget/visibility_change_widget.dart';

class MsgPage extends StatefulWidget {
  const MsgPage({super.key});

  @override
  State<MsgPage> createState() => _MsgPageState();
}

class _MsgPageState extends State<MsgPage> {
  final controller = Get.put(MsgController());

  @override
  Widget build(BuildContext context) {
    return VisibilityChangeWidget(
      visibilityKey: const ValueKey('MsgPage'),
      onVisibility: () {
        controller.refreshData();
      },
      child: GetBuilder<MsgController>(builder: (_) {
        var emptyType = controller.emptyType;
        var items = controller.sessionList;
        return emptyType != null || items.isEmpty
            ? EmptyLayout(
                type: emptyType ?? EmptyType.empty,
                hintText: 'No chat history yet',
              )
            : ListView.builder(
                physics: const BouncingScrollPhysics(),
                padding: EdgeInsets.only(top: 10.w, bottom: 10.w),
                itemBuilder: (context, index) {
                  return _buildItem(items[index]);
                },
                itemCount: items.length);
      }),
    );
  }

  Widget _buildItem(SesInfo item) {
    var message = item.message;
    var isSend = message?.userId == UserHelper().userId.toString();
    var isPrivateChat = message?.isPrivateChat ?? false;
    var isHide = !isSend && !IAPHelper().isVip && isPrivateChat;
    var unreadCount = item.unreadCount;
    String? content;
    var contentType = item.messageInfo?.msg.contentType;
    if (isHide) {
      content = '************';
    } else if (contentType == MsgContentType.waitAnswer) {
      content = '[Answering]';
    } else if (contentType == MsgContentType.image) {
      content = '[Picture]';
    } else if (contentType == MsgContentType.voice) {
      content = '[Voice]';
    } else if (contentType == MsgContentType.video) {
      content = '[Video]';
    } else {
      content = item.messageInfo?.msg.content;
    }
    var createTime = item.message?.createTime.millisecondsSinceEpoch ?? 0;
    return GestureDetector(
      onTap: () {
        ChatHelper().jumpToChatPage(RoleInfo.fromUserTbData(item.user));
      },
      behavior: HitTestBehavior.translucent,
      child: Container(
        width: double.infinity,
        height: 90.w,
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        margin: EdgeInsets.symmetric(
            horizontal: Dimens.mainHorizontalSpacing, vertical: 8.w),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            boxShadow: const [
              BoxShadow(
                  color: Color(0x0d000000),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 1.0, //阴影模糊程度
                  spreadRadius: 0.9 //阴影扩散程度
                  )
            ],
            color: Colors.white),
        alignment: Alignment.center,
        child: Row(
          children: [
            SizedBox(
              height: 50.w,
              width: 50.w,
              child: Stack(
                children: [
                  NetImageLoadUtils.loadCircle(item.avatar, 50.w),
                  if (unreadCount > 0)
                    Positioned(
                      top: 0,
                      right: 2.w,
                      child: Container(
                        width: 10.w,
                        height: 10.w,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.w),
                            color: const Color(0xffEE5065),
                            border:
                                Border.all(width: 1.5.w, color: Colors.white)),
                      ),
                    ),
                ],
              ),
            ),
            SizedBox(width: 8.w),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    width: double.infinity,
                    height: 22.w,
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            item.user?.nickname ?? '',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 18.sp,
                              color: Colors.black,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        Text(
                          createTime > 0
                              ? DateUtil.formatTimestamp(createTime)
                              : '',
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: AppColors.color_99,
                            fontWeight: FontWeight.w300,
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 2.w),
                  Container(
                    width: double.infinity,
                    height: 18.w,
                    alignment: Alignment.centerLeft,
                    child: Text(
                      content ?? '[No latest message]',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: AppColors.color_99,
                        fontWeight: FontWeight.w300,
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
